<?php
/* Add root path to include list. E.g. for easyer including from GUI files */
$includePath = realpath(dirname(__FILE__));
set_include_path($includePath);

/**
 * Connects to database or redirects to install
 * @return resource database link identifier 
 */
function db_connect(){
    /* Searching for seetings */
    $settingsFile = 'settings.php';
    if (!file_exists($settingsFile) && file_exists('../settings.php')) {
        $settingsFile = '../settings.php';
    }
    if(!file_exists($settingsFile)) require 'install.php';
    
    /* Connetcting to database */
    $settings = include $settingsFile;
    $handle = mysql_connect($settings['DB_HOST'], $settings['DB_USER'], $settings['DB_PASSWORD']);
    if($handle == false) die("Neprisijungiu prie MySQL.");
    mysql_query("SET NAMES utf8") or die("klaida del utf");
    mysql_query("SET CHARACTER SET utf8") or die("klaida del charseto");
    mysql_query("SET CHARACTER_SET_SERVER = utf8") or die("klaida del char SERVER");
    mysql_query("SET CHARACTER_SET_CONNECTION = utf8") or die("klaida del char CON");
    mysql_query("SET CHARACTER_SET_DATABASE = utf8") or die("klaida del char CON"); 
    $db = mysql_select_db($settings['DB_DATABASE']);
    if($db == false) die("Nepasirenku DB");
    return $handle;
}

/**
 * Common function to use with database
 */
class DB {
    /**
     * Executes mysql query.
     */
    public static function query($sql) {
        $result = mysql_query($sql);
        if ($result === false) {
            $nr = mysql_errno();
            $message = mysql_error();
            trigger_error("Error in sql query: $nr: $message \nSQL:\n$sql", E_USER_WARNING);
        }
        return $result;
    }
    
    /**
     * @return array numeric array of fields
     */
    public static function row($sqlResult) {
        return mysql_fetch_row($sqlResult);
    }
}

function db_close(){
    mysql_close();
}

?>
